#include "main.h"
#include "reconstruct.h"
#include "math.h"
#include "tim.h"
#include "dac.h"

#if 0
	//????
	#define POINTS 256
	#define SCALE_FACTOR (4095.0 / 2)  // ????,?[-1, 1]???[0, 4095]
	#define OFFSET 2048                // ???,?[0, 4095]?????
	#define M_PI  3.14159265
 
	uint16_t sine_wave_u16[POINTS];
	int sine_wave[POINTS];
	int square_wave[POINTS];
	void sina(void)
	{
		for (int i = 0; i < POINTS; i++)
		{
			double x = ((double) i / (POINTS - 1)) * 2 * M_PI;  // 0?2p????
			double sin_value = sin(x);  // ?????
			sine_wave[i] = (int) (SCALE_FACTOR * sin_value + OFFSET);  // ?????????0~4095??
			sine_wave_u16[i] = (uint16_t)sine_wave[i];
		}
	}
	
#else
	#define POINTS 256                             //??????
	#define MIN_VALUE 100                          //???????
	#define MAX_VALUE 4000                         //??????? 
	#define SCALE ((MAX_VALUE - MIN_VALUE) / 2.0)  
	#define OFFSET MIN_VALUE  
  #define M_PI  3.14159265
	
	uint16_t sine_wave_u16[POINTS];
	int sine_wave[POINTS];
	uint16_t square_wave_u16[POINTS];
	void sina(void) 
	{
 		for (int i = 0; i < POINTS; i++) {  
			double x = ((double)i / (POINTS - 1)) * 2 * M_PI;  // ??????0?2p????  
			double sin_value = sin(x);  // ?????  
			sine_wave[i] = (int)((sin_value + 1) * SCALE + OFFSET);  // ?????????100~4000?? 
		  sine_wave_u16[i] = (uint16_t)sine_wave[i];	
		}
		
 		for (int i = 0; i < POINTS/2; i++) square_wave_u16[i] = MIN_VALUE;
 		for (int i = POINTS/2; i < POINTS; i++) square_wave_u16[i] = MAX_VALUE;
	}
	
#endif

void start_output(unsigned short output_Hz, char wave_type){
	extern uint16_t user_hz;
	HAL_TIM_Base_Stop(&htim6);
	user_hz = output_Hz;
	MX_TIM6_Init();
	HAL_TIM_Base_Start(&htim6);
	if(wave_type) HAL_DAC_Start_DMA(&hdac, DAC_CHANNEL_1, (uint32_t *)square_wave_u16, POINTS, DAC_ALIGN_12B_R);
	else HAL_DAC_Start_DMA(&hdac, DAC_CHANNEL_1, (uint32_t *)sine_wave_u16, POINTS, DAC_ALIGN_12B_R);
}

void stop_output(){
	HAL_DAC_Stop_DMA(&hdac, DAC_CHANNEL_1);
	HAL_TIM_Base_Stop(&htim6);
}
